package com.atguigu.gmall.mq.receiver;

import com.atguigu.gmall.mq.config.DelayedMqConfig;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class DelayedReceiver {

    @Autowired
    private RedisTemplate redisTemplate;


    @RabbitListener(queues = DelayedMqConfig.queue_delay_1)
    @SneakyThrows
    public void delayed(String msg, Message message, Channel channel){

        //定义key
        String key="delay:"+msg;
        //设置标记
        Boolean result = redisTemplate.opsForValue().setIfAbsent(key, "0", 10, TimeUnit.MINUTES);
        //判断
        if(!result){
            //说明已经来过了，我们需要判断是否消费了
            String flag = (String) redisTemplate.opsForValue().get(key);
            //判断
            if("0".equals(flag)){
                System.out.println("接收消息内容：\t"+msg);
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                System.out.println("接收消息时间：\t"+simpleDateFormat.format(new Date()));

                redisTemplate.opsForValue().set(key,"1",10, TimeUnit.MINUTES);
                //消息确认
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

             return ;

            }else{


                //消息确认
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

                return;
            }


        }


        System.out.println("接收消息内容：\t"+msg);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("接收消息时间：\t"+simpleDateFormat.format(new Date()));
        redisTemplate.opsForValue().set(key,"1",10, TimeUnit.MINUTES);
        //消息确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

    }

}
